package pri.hillchen.std.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 9:59 2018/3/5 0005.
 */
public class NioFileCopyDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("C:\\temp\\niotest\\javacore.20180208.102243.39817.0002.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\temp\\niotest\\nioCopyTest.txt");
        FileOutputStream fileOutputStream2 = new FileOutputStream("C:\\temp\\niotest\\nioCopyTest2.txt");

        FileChannel sourceFc = fileInputStream.getChannel();
        FileChannel targetFc = fileOutputStream.getChannel();
        FileChannel targetFc2 = fileOutputStream2.getChannel();


        targetFc2.transferFrom(sourceFc,0,sourceFc.size());

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //往buffer中写数据
        while (sourceFc.read(byteBuffer)>=0){
            //翻转buffer为数据读取状态
            byteBuffer.flip();
            targetFc.write( byteBuffer );
            //清除buffer中数据，将buffer重复利用
            byteBuffer.clear();
        }


        fileOutputStream2.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}
